﻿using UnityEngine;
using System.Collections;

public class EnemyController : MonoBehaviour {
	
	public bool hacked = false;
	
	private UILabel codeLabel;
	
	private UISlider hackSlider;
	
	public string destructCode = "";
	
	float hackSpeed = 0.2f;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	public void Initialize(float _movementDuration)
	{
		Vector2 bgSize = transform.parent.parent.FindChild("Background").GetComponent<UISprite>().localSize;
		Vector2 spriteSize = transform.FindChild("Sprite").GetComponent<UISprite>().localSize;
		
		transform.localPosition = new Vector3(Random.Range(spriteSize.x * 0.5f, bgSize.x - spriteSize.x * 0.5f), 
			-spriteSize.y *0.5f, 0);
		
		TweenPosition.Begin(gameObject, _movementDuration, new Vector3(transform.localPosition.x , 
			-bgSize.y + spriteSize.y *0.5f, 0));
		
		GetComponent<UIForwardEvents>().target = transform.parent.parent.gameObject;
		
		hackSlider = transform.FindChild("DestructCode").GetComponent<UISlider>();
		
		codeLabel = hackSlider.transform.FindChild("Label").GetComponent<UILabel>();		
	}
	
	public IEnumerator Kill()
	{
		TweenScale.Begin(gameObject, 0.2f, Vector3.zero);
		
		collider.enabled = false;
		
		yield return new WaitForSeconds(0.2f);
		
		EnemySpawnController.instance.EnemyDestroyed(this);
		
		Destroy(gameObject);
	}
	
	
	void OnTriggerEnter(Collider other)
	{
		ActiveBarrierController barrierController = other.GetComponent<ActiveBarrierController>();
		
		if( barrierController != null)
		{
			print ("OnTriggerEnter barrierObject");
			barrierController.HitByEnemy(this);
		}
		
		if( other.CompareTag("DamageZone"))
		{
			print ("OnTriggerEnter endofzone");
			HealthController.Instance.Damage(30f);
			
			StartCoroutine(Kill());
			
			return;
		}
	}
	
	public void SetDesctuctCode(string randomWorkKey)
	{
		if( !string.IsNullOrEmpty(randomWorkKey))
		{
			destructCode = Localization.instance.Get(randomWorkKey);
			
			codeLabel.text = Localization.instance.Get("CodeEncrypted");
		}
		else
		{
			hackSlider.gameObject.SetActive(false);
		}
	}
	
	
	IEnumerator Hack()
	{
		codeLabel.text = Localization.instance.Get("Hacking");
		
		while(hackSlider.value < 1)
		{
			hackSlider.value += Time.deltaTime* hackSpeed;
			
			yield return null;
		}
		
		hackSlider.value = 1;
		hacked = true;
		codeLabel.text = "[99ff99]" + destructCode;		
	}
	
	void OnClick()
	{
		if( !string.IsNullOrEmpty(destructCode))
		{
			StartCoroutine(Hack());
		}
	}
	
	
}
